import random
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import time
import os


def check_code():
    """
    生成6位随机验证码的函数
    """
    codes = ""
    for _ in range(6):
        code = str(random.randint(0, 9))
        codes += code
    return codes


def send_code(from_addr, password, to_addr):
    """
    发送邮件验证码的函数
    :param from_addr: 发件邮箱地址
    :param password: 发件邮箱的SMTP授权码
    :param to_addr: 收件邮箱地址
    """
    check_codes = check_code()
    print(check_codes)
    smtp_server = 'smtp.qq.com'
    # 构建邮件正文内容，适当丰富正文说明
    msg = MIMEText(f'您好，您正在进行相关操作，以下是本次操作的验证码：{check_codes}，请妥善保管，勿向他人透露。', 'plain',
                   'utf-8')
    # 修改发件人From字段格式
    msg['From'] = Header(from_addr)
    msg['To'] = Header(to_addr)
    msg['Subject'] = Header('验证码测试邮件')

    try:
        server = smtplib.SMTP_SSL(smtp_server)
        server.connect(smtp_server, 465)
        server.login(from_addr, password)
        server.sendmail(from_addr, to_addr, msg.as_string())
        server.quit()
        print('验证码已发送到您的邮箱中，请注意查收...')
        return check_codes
    except smtplib.SMTPException as e:
        print(f'验证码发送失败，原因: {e}，请稍后重试，或反馈客服wotemo@qq.com')
        return None


def checking():
    """
    整体的验证码发送与验证流程控制函数
    """
    # 发件邮箱地址，替换为你自己有效的邮箱
    from_addr = '1164428950@qq.com'
    # 收件邮箱地址，可根据需求修改为要发送的指定邮箱
    to_addr = "xlm20040219@qq.com"
    # 从环境变量中获取SMTP授权码 参考文章：https://blog.csdn.net/zzq900503/article/details/84977468
    password = os.environ["SMTP_PASSWORD"]
    print(password)

    check_codes = send_code(from_addr, password, to_addr)
    if check_codes is None:
        return

    time_start = time.time()
    while True:
        check_code_input = input('请输入您的验证码：')
        time_end = time.time()
        time_continue = time_end - time_start
        if time_continue > 300:
            print('验证码超时，请稍后重试...')
            break
        if check_code_input == check_codes:
            print('验证通过，请继续您的操作...')
            break
        else:
            print('验证码错误，请重试...')
    return to_addr


if __name__ == "__main__":
    checking()